<template>
    <div class="pay_baohutong">
        <!-- 查询 -->
        <div class="zw-form-layout">
            <el-form ref="formRef" :model="form" label-width="auto">
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="商户信息" prop="keywords">
                            <el-input
                                v-model.trim="form.keywords"
                                clearable
                                placeholder="请输入商户名称/简称/统一社会信用代码"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="主体类型" prop="main_type">
                            <el-select v-model="form.main_type" placeholder="全部类型" clearable>
                                <el-option
                                    v-for="item in mainType"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-show="defaultExpand">
                        <el-form-item label="开户进度" prop="status">
                            <el-select v-model="form.status" placeholder="全部类型" clearable>
                                <el-option
                                    v-for="item in accountStatus"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-show="defaultExpand">
                        <el-form-item label="创建时间" prop="created_at">
                            <el-date-picker
                                v-model="form.created_at"
                                type="daterange"
                                clearable
                                :default-time="defaultTime"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                :disabled-date="disabledDate" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-show="defaultExpand">
                        <!-- <el-form-item label="更新时间" prop="updated_at">
                            <el-date-picker
                                v-model="form.updated_at"
                                type="daterange"
                                clearable
                                :default-time="defaultTime"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                :disabled-date="disabledDate" />
                        </el-form-item> -->
                    </el-col>
                    <el-col :span="8" class="zw-form-btns">
                        <el-button type="primary" @click="searchHandler">查询</el-button>
                        <el-button plain class="btn-reset" @click="resetHandler">清空</el-button>
                        <el-button
                            v-if="defaultExpand"
                            class="icon_btn"
                            :text="true"
                            type="primary"
                            @click="handleExpand">
                            收起<el-icon><ArrowUp /></el-icon>
                        </el-button>
                        <el-button v-else class="icon_btn" :text="true" type="primary" @click="handleExpand">
                            展开<el-icon><ArrowDown /></el-icon>
                        </el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div class="pay_baohutong_bottom" :class="{ pay_baohutong_bottom_expand: !defaultExpand }">
            <!-- 按钮 -->
            <div class="btn-group">
                <!-- 开通账户 -->
                <OpenAccountDialog />
            </div>
            <!-- 列表 -->
            <el-table
                ref="tableRef"
                :data="tableList"
                :height="tableHeight"
                type="expand"
                :default-expand-all="false"
                row-key="id"
                :row-class-name="getClass"
                :class="{ 'el-table-empty': !tableList?.length }"
                :expand-row-keys="expandRowKeys">
                <el-table-column type="expand" width="1">
                    <template #default="{ row }">
                        <AccountList
                            v-if="row.status != 10"
                            :id="row?.id"
                            :key="row.id"
                            :list="row?.isp_info"
                            :openNo="row.open_no"></AccountList>
                    </template>
                </el-table-column>
                <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                    <template v-if="prop === 'corp_name'" #header>
                        <span class="p-l-5">商户信息</span>
                    </template>
                    <template #default="{ row }">
                        <template v-if="prop === 'corp_name'">
                            <div class="corp-name">
                                <div class="corp-name-main">
                                    <!-- <el-tooltip placement="top" :content="row.corp_name" :show-after="800">
                                        <span>{{ row.corp_name || '--' }}</span>
                                    </el-tooltip> -->
                                    <ZwTooltip :content="row.corp_name" :line="2"></ZwTooltip>
                                </div>
                                <div class="corp-name-sub" v-if="row.corp_unified_social_credit_code">
                                    <!-- <el-tooltip
                                        placement="top"
                                        :content="row.corp_unified_social_credit_code"
                                        :show-after="800">
                                        <span>{{ row.corp_unified_social_credit_code }}</span>
                                    </el-tooltip> -->
                                    <ZwTooltip :content="row.corp_unified_social_credit_code"></ZwTooltip>
                                </div>
                            </div>
                        </template>
                        <template v-if="prop === 'status_name'">
                            <span
                                class="custom-status-point"
                                :style="{ '--status-bgcolor': StatusColorOption[row.status] }">
                                {{ row.status_name }}
                            </span>
                        </template>
                        <template v-if="prop === 'operations'">
                            <span
                                v-for="{ label, fn, ref } in row.operations"
                                :key="label"
                                @click="fn(row, ref)"
                                size="small"
                                class="table-button button--small"
                                >{{ label }}</span
                            >
                        </template>
                    </template>
                </el-table-column>
                <template #empty>
                    <div class="table-empty">
                        <img
                            src="https://img.static-keyid.cn/toolspace/scrm/2023/10/1697683499137ngcb4fpdwjr9ijb4.png" />
                        <div>{{ noDataText }}</div>
                    </div>
                </template>
            </el-table>
            <!-- 分页 -->
            <Pagination
                class="custom-bottom-page"
                :total="totalCount"
                :page-size="form.page_size"
                :current-page="form.page"
                @sizeChange="changeSizeHandler"
                @pageChange="changePageHandler" />
        </div>
    </div>
</template>

<script setup name="payAccountList">
import { ref, reactive, computed, onActivated, onDeactivated, h, nextTick } from 'vue';
import { onBeforeRouteLeave, useRouter } from 'vue-router';
import request from '@/request/index';
import constants from '@/commons/constants';
import { packSelectObjUtil, cloneDeep, isDayAfter, isEmpty, confirmHandler } from '@/commons/utils';
import { setLayout, resetLayout, resizeTableHeight, getTableHeight, resizeTableRemove } from '@/hooks/layout';
import Pagination from '@/components/Pagination.vue';
import ZwTooltip from '@/components/ZwTooltip.vue';
import OpenAccountDialog from './openAccountDialog.vue';
import AccountList from './accounts.vue';

const router = useRouter(); // 路由

const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]; // 默认日期
const accountStatus = reactive(packSelectObjUtil(constants.ACCOUNT_STATUS)); // 账号状态
const mainType = reactive(packSelectObjUtil(constants.MAIN_TYPE)); // 主体类型

const form = reactive({
    page: 1, //页码数
    page_size: 10, //每页显示数
    keywords: '', //商户信息 商户名称/简称/统一社会代码
    main_type: null, //主体类型 1-企业商户 2-个人工商户 3-个人商户
    status: null, //开户进度 10.草稿中 20.开户中 30.开户完成
    created_at: [], //创建时间
    updated_at: [] //更新时间
}); // 查询表单
let formClone = reactive(cloneDeep(form)); // 查询备份
const formRef = ref(null); // form ref
const tableRef = ref(null);
const totalCount = ref(0); // 数据总数
let tableList = reactive([]); // 表格数据
let defaultExpand = ref(true); // 展开/收起

// 控制查询展开收起
const handleExpand = () => {
    defaultExpand.value = !defaultExpand.value;
    setTimeout(() => {
        getTableHeight('pay_baohutong_bottom', tableHeight, 'custom-bottom-page');
    });
};
// 禁止查询的日期
const disabledDate = date => {
    return isDayAfter(date);
};

// 进度状态颜色
const StatusColorOption = {
    10: '#EAEAEA', // 草稿中
    20: '#FF6B00', // 开户中
    30: '#60B900' // 开户完成
};
const tableColumns = computed(() => {
    const baseTableColumns = [
        { label: '商户信息', prop: 'corp_name', minWidth: '300' },
        { label: '主体类型', prop: 'corp_main_type_name', minWidth: '170' },
        { label: '产品能力', prop: 'capacity_code_name_str', minWidth: '170' },
        { label: '账户状态', prop: 'status_name', minWidth: '170' },
        { label: '创建时间', prop: 'created_at', minWidth: '170' },
        { label: '操作', prop: 'operations', width: '170', fixed: 'right' }
    ];
    return baseTableColumns;
});
// 获取行class
const getClass = ({ row }) => {
    if (row.status != 10 && row?.isp_info?.length) {
        return 'not-border';
    }
};
// 设置默认展开行
const expandRowKeys = computed(() => {
    // 默认展开行
    return tableList.reduce((pre, cur) => {
        if (cur.status != 10 && cur?.isp_info?.length) {
            pre.push(cur.id);
        }
        return pre;
    }, []);
});
// 空数据文案
const noDataText = computed(() => {
    const hasValue = Object.keys(formClone).some(
        key => !['page', 'page_size'].includes(key) && !isEmpty(formClone[key])
    );
    return hasValue ? '暂无数据' : '您尚未开通收款账户，请前往开通';
});

// 以下有时间抽离成公共查询js
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    formClone.page = form.page;
    queryListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.page_size = perPage;
    formClone.page = form.page;
    formClone.page_size = form.page_size;
    queryListHandler();
};

/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    searchHandler();
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    Object.assign(formClone, cloneDeep(form));
    queryListHandler();
};

/**
 * 分页查询
 */
// let loading = ref(false);
const queryListHandler = async notScroll => {
    // loading.value = true;
    const _form = cloneDeep(formClone);
    const res = await request('accountManageList', _form);
    // loading.value = false;
    const list = (res?.data?.data || [])?.map(item => {
        // 根据不同状态显示不同按钮
        // 3已失效 4已过期 5未启用 6已启用
        const btns = {
            0: { label: '查看', fn: routerHandler, ref: 'viewRef' },
            1: { label: '编辑', fn: routerHandler, ref: 'editRef' },
            2: { label: '删除', fn: removeAccount, ref: 'removeRef' },
            3: { label: '修改资料', fn: routerHandler, ref: 'editRef' },
            4: { label: '开启收单服务', fn: acquireAccount, ref: 'openRef' }
        };
        // 产品能力
        const { capacity_code_name } = item;
        item.capacity_code_name_str =
            capacity_code_name && capacity_code_name.length ? capacity_code_name.join('；') : '--';
        item.operations = [];
        if (item.status == 10) {
            // 草稿中
            item.operations = [btns[0], btns[1], btns[2]];
        } else {
            item.operations = [btns[0]];
            // is_edit 1可编辑，2不可编辑
            if (item.is_edit == 1) {
                // 如果是修改状态
                item.operations.push(btns[3]);
            }
            // 是否展示开启收单服务按钮  item.is_open 1-展示 2-不展示
            if (item.is_open_acquring == 1) {
                // 如果是未开启收单服务,且已开通的商户
                item.operations.push(btns[4]);
            }
        }
        return item;
    });
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = res.data.total;
    nextTick(() => {
        // 加载数据后将table滚动条滚动到table最顶部和最左边
        !notScroll && tableRef?.value?.scrollTo(0, 0);
    });
};

/**
 * 跳转编辑/查看/修改资料/页面
 */
const routerHandler = (row, ref) => {
    const paths = {
        viewRef: '/pay/account/view',
        editRef: '/pay/account/edit'
    };
    router.push({
        path: paths[ref],
        query: { id: row.id }
    });
};

/**
 * 删除
 */
const removeAccount = row => {
    confirmHandler({
        params: ['accountManageDelete', { id: row.id }],
        title: `确定要删除商户【${row.corp_name}】吗？ `,
        subTitle: '删除后，该商户填写的资料将全部删除。',
        callback: queryListHandler,
        successMsg: '删除成功'
    });
};

/**
 * 开启收单服务回调函数
 */
const acquireAccountCallback = () => {
    queryListHandler(true);
};
/**
 * 开启收单服务
 */
const acquireAccount = row => {
    // 接口名称accountManageOpenAcquiring
    confirmHandler({
        params: ['accountManageOpenAcquiring', { id: row.id }],
        title: `确定要为商户【${row.corp_name}】开启收单服务吗？ `,
        subTitle: '开启收单服务后，需要法人/联系人进行微信和支付宝的认证和授权，完成认证授权后支持微信、支付宝收单。',
        callback: acquireAccountCallback,
        successMsg: '开启成功'
    });
};

// 页面可见监听函数
const visibilitychange = () => {
    if (document.visibilityState === 'visible') {
        queryListHandler();
    }
};

const getAllData = () => {
    queryListHandler();
};

let tableHeight = ref(300);
onActivated(() => {
    // Object.keys(formClone || {})?.forEach(key => {
    //     form[key] = formClone[key];
    // });
    setLayout('pay-baofutong-layout');
    getAllData();
    setTimeout(() => {
        resizeTableHeight('pay_baohutong_bottom', tableHeight, 'custom-bottom-page');
    }, 0);

    // useDocumentVisibility('add', visibilitychange);
});
onDeactivated(() => {
    resetLayout('pay-baofutong-layout');
    resizeTableRemove();
    // useDocumentVisibility('remove', visibilitychange);
});

onBeforeRouteLeave((to, from, next) => {
    next();
});
</script>
<style lang="scss">
.pay-baofutong-layout {
    height: 100%;
    padding: 0 !important;
    background-color: #f3f3f3 !important;
}
.not-border td.el-table__cell {
    border-bottom: 0;
}
.p-l-5 {
    padding-left: 5px;
}
</style>
<style lang="scss" scoped>
@import './scss/index.scss';
</style>
